package ca.ericslandry.server.handler;

import com.google.appengine.api.datastore.EntityNotFoundException;

import net.customware.gwt.dispatch.server.ActionHandler;
import net.customware.gwt.dispatch.server.ExecutionContext;
import net.customware.gwt.dispatch.shared.ActionException;
import ca.ericslandry.server.dao.IssueDAO;
import ca.ericslandry.server.dao.ShardedCounter;
import ca.ericslandry.shared.domain.Issue;
import ca.ericslandry.shared.rpc.GetIssue;
import ca.ericslandry.shared.rpc.GetIssueResult;

public class GetIssueHandler implements ActionHandler<GetIssue, GetIssueResult> {
	@Override
	public GetIssueResult execute(GetIssue action, ExecutionContext context) throws ActionException {
		IssueDAO dao = new IssueDAO();
		Issue issue;
		try {
			issue = dao.get(action.getId());
			ShardedCounter counter = new ShardedCounter(issue.toString());
			counter.increment();
			issue.setViewCount(counter.getCount());

		} catch (EntityNotFoundException e) {
			throw new ActionException("No issue was found with id " + action.getId(), e);
		}
		return new GetIssueResult(issue);
	}

	@Override
	public Class<GetIssue> getActionType() {
		return GetIssue.class;
	}

	@Override
	public void rollback(GetIssue action, GetIssueResult result, ExecutionContext context) throws ActionException {
		// Nothing to do here
	}
}
